package com.neomanager.admin.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.neomanager.admin.dao.AdminDao;
import com.neomanager.admin.dao.AuthDao;
import com.neomanager.admin.dao.MenuDao;
import com.neomanager.login.model.AdminInfo;
import com.util.JspMaker;
import com.util.UtilCommon;

@Controller
@SessionAttributes("adminInfo")
public class AuthController
{
	private final Logger logger = Logger.getLogger(this.getClass());
	@Resource(name="AuthDao")
	AuthDao auth;
	@Resource(name="MenuDao")
	MenuDao menu;
	@Resource(name="AdminDao")
	AdminDao admin;

	private String userId = null;

	/**
	 * 권한 관리 페이지 -  관리자 목록
	 */
	@RequestMapping(value = "/admin/authmng_list.do", method = RequestMethod.GET)
	public String listAuthmng(@RequestParam Map<String, Object> commandMap, Model model,
			HttpServletRequest request, HttpServletResponse response)
	{
		logger.info("관리자 목록.");
	    HttpSession session = request.getSession();
	    AdminInfo aInfo = (AdminInfo) session.getAttribute( "adminInfo" );
		String id = aInfo.getAdmin_id();
		String menuFile = "../menu/" + id + "_menu.jsp";

		// 현재 페이지
		int page = 1;
		if (commandMap.get("page") != null)
			page = Integer.parseInt(commandMap.get("page").toString());

		// 페이지당 목록 수
		int pageCount = 10;

		// 시작번호
		int startNo = (page - 1) * pageCount;

		commandMap.put("page", page);
		commandMap.put("pageCount", pageCount);
		ArrayList<Map<String, Object>> listMap = admin.selectAdminInfo(commandMap);

		// 총 갯수
		int totalCount = 0;
		if ( listMap != null )
		{
			Map<String, Object> rs = listMap.get(0);
			totalCount = Integer.parseInt( rs.get("TOTALCOUNT").toString() );
		}

		// 페이징 처리
		if (totalCount > 0)
		{
			UtilCommon util = new UtilCommon();
			// 총게시물수, 페이지당 목록수, 현재페이지, 블럭당 나타낼 페이지 수
			util.setPage(totalCount, pageCount, page, 10);
			commandMap.put("totalCount", totalCount);
			commandMap.put("totalPage", util.getTotalPage());
			commandMap.put("startPage", util.getStartPage());
			commandMap.put("endPage", util.getEndPage());
			commandMap.put("startNo", startNo);
		}

		model.addAttribute("menuinclude", menuFile);
		model.addAttribute("adminInfo", aInfo);
		model.addAttribute("commandMap", commandMap);
		model.addAttribute("listMap", listMap);

		return "admin/authmng_list";
	}

	/**
	 * 권한 관리 팝업 페이지
	 */
	@RequestMapping(value = "/admin/authmng_popup.do", method = RequestMethod.GET)
	public String listAdminmngPopup(@RequestParam Map<String, Object> commandMap, Model model,
			HttpServletRequest request, HttpServletResponse response)
	{
		logger.info("권한 관리 팝업 페이지");
		userId = request.getParameter("userId");
		ArrayList<Map<String, Object>> listMapAuth = auth.selectMenuInfoById(userId);
		model.addAttribute("listMapAuth", listMapAuth);

		return "admin/authmng_popup";
	}


	/**
	 * 권한 변경 처리
	 */
	@RequestMapping(value = "/admin/authmng_popup_proc.do", method = RequestMethod.POST)
	public void progressAuth(@RequestParam(value="read[]", required=true) List<Object> readList,
							 @RequestParam (value="write[]", required=true) List<Object> writeList,
							 Map<String, Object> commandMap, Model model, HttpServletRequest request, HttpServletResponse response)
	{
		logger.info("권한 변경 처리");

		ArrayList<Map<String, Object>> listMap = menu.selectMenuInfoList(readList);
		auth.deleteAuthInfoById(userId);

		// make jsp contents
		String content = "String[][] menuArr = {\r\n";
		for (int i = 0; i < listMap.size(); i++)
		{
			commandMap.put("menu_sid", listMap.get(i).get("MENU_SID"));
			commandMap.put("admin_id", userId);

			//쓰기 권한 여부 체크 로직
			for (int j = 0; j < writeList.size(); j++)
			{
				if (listMap.get(i).get("MENU_SID").equals(writeList.get(j))) {
					commandMap.put("write_auth", "Y");
					break;
				}else{
					commandMap.put("write_auth", "N");
				}
			}

			//insert Auth_data into Auth_table
			auth.insertAuthInfo(commandMap);

			content += "{\""+listMap.get(i).get("MENU_SID")+"\",\""
					+ listMap.get(i).get("MENU_NAME")+"\",\""
					+ listMap.get(i).get("MENU_URL")+"\",\""
					+ listMap.get(i).get("MENU_DEPTH")+"\",\""
					+ listMap.get(i).get("PARENT_SID")+"\",\""
					+ listMap.get(i).get("MENU_PATH")+"\",\""
					+ listMap.get(i).get("MENU_PATHNAME")+"\",\""
					+ listMap.get(i).get("SUPER_YN")+"\",\""
					+ commandMap.get("write_auth")+"\"},\r\n";
		}// end for

		JspMaker jspMaker = new JspMaker();
		String path = request.getSession().getServletContext().getRealPath(""); //servelt rootpath 구하기
		logger.info(path);

		jspMaker.makeJspFile(content, userId, path);
	}
}
